<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Local Audio Rendering Demo</title>
<script type="text/javascript" src="../../base/adapter.js"></script>
<script>
  var audioElement;
  var buttonStart;
  var buttonStop;
  var localStream;
  
  $ = function(id) {
    return document.getElementById(id);
  };

  function start() {
    var constraints = {audio:true, video:false};
    getUserMedia(constraints, gotStream, gotStreamFailed);
    buttonStart.disabled = true;
    buttonStop.disabled = false;
  }
  
  function stop() {
    buttonStart.enabled = true;
    buttonStop.enabled = false;
    localStream.stop();
  }
  
  function gotStream(stream) {
    videoTracks = stream.getVideoTracks();
    audioTracks = stream.getAudioTracks();
    if (audioTracks.length == 1 && videoTracks.length == 0) {
      console.log('gotStream({audio:true, video:false})');
      console.log('Using audio device: ' + audioTracks[0].label);
      attachMediaStream(audioElement, stream);
      stream.onended = function() {
        console.log('stream.onended');
        buttonStart.disabled = false;
        buttonStop.disabled = true;
      };
      
      localStream = stream;
    } else {
      alert('The media stream contains an invalid amount of audio tracks.');
      stream.stop();
    }
  }
  
  function gotStreamFailed(error) {
    buttonStart.disabled = false;
    buttonStop.disabled = true;
    alert('Failed to get access to local media. Error code: ' + error.code);
  }
  
  function onload() {
    audioElement = $('audio');
    buttonStart = $('start');
    buttonStop = $('stop');
    buttonStart.enabled = true;
    buttonStop.disabled = true;
  } 
</script>
</head>

<body onload="onload()">
  <h2>Rendering of a local media stream using &lt;audio&gt;</h2>
  <p>Demonstrates usage of a local media stream connected to an HTML5 audio tag.<br>
     Press Start, select a microphone and listen to your own voice in loopback.</p>
  <style>
    button {
      font: 14px sans-serif;
      padding: 8px;
    }
  </style>
  <audio id="audio" autoplay="autoplay" controls="controls"></audio><br><br>
  <button id="start" onclick="start()">Start</button>
  <button id="stop" onclick="stop()">Stop</button>
</body>
</html>
